
var isSwitchOn = true;
var imageUrl = ""//
var upscaleImageUrl = ""
var isUpscale = false;
var isRemoveBg = false;
var imgUrl = localStorage.getItem('dict_img')

// 打开弹窗函数
function openModal() {
    modal.style.display = 'block';
    overlay.style.display = 'block';
}
// 关闭弹窗函数
function closeModal() {
    modal.style.display = 'none';
    overlay.style.display = 'none';
}

function hiddenEle() {
    document.addEventListener('DOMContentLoaded', function () {
        var footerMetaElement = document.querySelector('.post-footer__meta');
        if (footerMetaElement) {
            var lastChild = footerMetaElement.lastElementChild;
            if (lastChild) {
                lastChild.style.marginBottom = '0';
                lastChild.style.display = 'none';
            } else {
                console.error('No child elements found in .post-footer__meta');
            }
        } else {
            console.error('Element with class .post-footer__meta not found');
        }

        // 隐藏 .post-entry__meta 元素
        var postEntryMetaElements = document.querySelectorAll('.post-entry__meta');
        postEntryMetaElements.forEach(function (element) {
            element.style.display = 'none';
        });

        // 隐藏 .post-title__meta 元素
        var postTitleMetaElements = document.querySelectorAll('.post-title__meta');
        postTitleMetaElements.forEach(function (element) {
            element.style.display = 'none';
        });
        var footerElement = document.querySelector('.footer');
        if (footerElement) {
            var lastChild = footerElement.lastElementChild;
            if (lastChild) {
                lastChild.style.marginBottom = '0';
                lastChild.style.display = 'none';
            } else {
                console.error('No child elements found in .post-footer__meta');
            }
        } else {
            console.error('Element with class .post-footer__meta not found');
        }
    });
}
function setupUI() {
    
    hiddenEle()
    var elements = document.querySelector('.post-title__text');
    elements.textContent = localStorage.getItem('dict_name');
   
    
    var container = document.getElementById("img-wrapper");
    var newImg = document.createElement("img");
    newImg.classList.add("individual-images");

    var decodedUrl = decodeURIComponent(imgUrl);
    newImg.src = decodedUrl;
    container.appendChild(newImg);
    // 获取弹窗相关元素
    const modal = document.getElementById('modal');
    const overlay = document.getElementById('overlay');
    const closeModalBtn = document.getElementById('closeModalBtn');
}
function setupPopup() {
    // 为每个按钮添加点击事件，点击时打开弹窗
    document.getElementById('button1').addEventListener('click', openModal);
    // document.getElementById('button2').addEventListener('click', removebg);
    // document.getElementById('button3').addEventListener('click', upscale);

    // 关闭弹窗事件
    closeModalBtn.addEventListener('click', closeModal);
    overlay.addEventListener('click', closeModal);

    document.getElementById('modalButton1').addEventListener('click', function () {
        if (isSwitchOn) {
            var hiddenImage = document.getElementById("hiddenImage");
            hiddenImage.src = 'images/m1.png';
            hiddenImage.style.display = 'block';
        }
    });
    document.getElementById('modalButton2').addEventListener('click', function () {
        if (isSwitchOn) {
            var hiddenImage = document.getElementById("hiddenImage");
            hiddenImage.src = 'images/m2.png';
            hiddenImage.style.display = 'block';
        }
    });
    document.getElementById('modalButton3').addEventListener('click', function () {
        if (isSwitchOn) {
            var hiddenImage = document.getElementById("hiddenImage");
            hiddenImage.src = 'images/m3.png';
            hiddenImage.style.display = 'block';
        }
    });
    document.getElementById('modalButton4').addEventListener('click', function () {
        if (isSwitchOn) {
            var hiddenImage = document.getElementById("hiddenImage");
            hiddenImage.src = 'images/m4.png';
            hiddenImage.style.display = 'block';
        }
    });

    // document.getElementById('switchButton').addEventListener('change', function () {
    //     if (this.checked) {
    //         console.log('SwitchButton is ON');
    //     } else {
    //         console.log('SwitchButton is OFF');
    //     }
    //     isSwitchOn = this.checked;
    //     // 保存状态到 localStorage
    //     localStorage.setItem('isSwitchOn', isSwitchOn);
    //     if (isSwitchOn) {
    //         document.getElementById('hiddenImage').style.display = 'block';
    //     } else {
    //         document.getElementById('hiddenImage').style.display = 'none';
    //     }
    // });
}

function removebg() {
    if (isRemoveBg) {
        isRemoveBg = false;
        var images = document.querySelectorAll(".individual-images");
        images.forEach(img => {
            img.src = imgUrl;
        });

    } else {
        isRemoveBg = true;
        if (imageUrl == '') {
            removeBgFromImage(imgUrl);
        } else {
            var images = document.querySelectorAll(".individual-images");
            images.forEach(img => {
                img.src = imageUrl;
            });
        }
    }
}
function upscale() {
    if (isUpscale) {
        isUpscale = false;
        var images = document.querySelectorAll(".individual-images");
        images.forEach(img => {
            img.src = imgUrl;
            const linkElement = document.querySelector('a[data-fancybox="gallery"]');
            // 设置新的图片链接
            const newImageLink = imgUrl;
            // 更改<a>元素的href属性
            linkElement.setAttribute('href', newImageLink);
        });

    } else {
        isUpscale = true;
        if (upscaleImageUrl == '') {
            sendUpscaleRequest(imgUrl);
        } else {
            var images = document.querySelectorAll(".individual-images");
            images.forEach(img => {
                img.src = upscaleImageUrl;

                const linkElement = document.querySelector('a[data-fancybox="gallery"]');
                // 设置新的图片链接
                const newImageLink = upscaleImageUrl;
                // 更改<a>元素的href属性
                linkElement.setAttribute('href', newImageLink);
            });
        }
    }
}
async function removeBgFromImage(url) {
    const apiKey = 'UmGTjNKYxvJeawTdqb9CnUfA';
    var loading_overlay = document.getElementById('loading_overlay');
    loading_overlay.style.display = 'flex';
    fetch('https://api.remove.bg/v1.0/removebg', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Api-Key': 'zWEz8SiyH4uqhEFRgASjJM3v'
        },
        body: JSON.stringify({
            image_url: url
        })
    })
        .then(response => response.blob())
        .then(blob => {
            loading_overlay.style.display = 'none';
            imageUrl = URL.createObjectURL(blob);
            var images = document.querySelectorAll(".individual-images");
            images.forEach(img => {
                img.src = imageUrl;
            });
        })
        .catch(error => {
            loading_overlay.style.display = 'none';
            console.error('Error:', error);
        });
}

async function sendUpscaleRequest(url) {
    var loading_overlay = document.getElementById('loading_overlay');
    loading_overlay.style.display = 'flex';
    const apiUrl = 'https://ai-picture-upscaler.p.rapidapi.com/upscaler/v2/';
    const data = new FormData();
    data.append('image_url', url);
    data.append('scale', '2');

    const options = {
        method: 'POST',
        headers: {
            'x-rapidapi-key': 'f484503efbmshdcfd476dce80086p1503ddjsn7ce94113c2b9',
            'x-rapidapi-host': 'ai-picture-upscaler.p.rapidapi.com'
        },
        body: data
    };

    try {
        const response = await fetch(apiUrl, options);
        const result = await response.text();
        const jsonData = JSON.parse(result);
        const result_url = jsonData.result_url;
        loading_overlay.style.display = 'none';
        upscaleImageUrl = result_url
        var images = document.querySelectorAll(".individual-images");
        images.forEach(img => {
            img.src = result_url;
            // 找到包含要更改的链接的<a>元素
            const linkElement = document.querySelector('a[data-fancybox="gallery"]');
            // 设置新的图片链接
            const newImageLink = result_url;
            // 更改<a>元素的href属性
            linkElement.setAttribute('href', newImageLink);
        });
        console.log(upscaleImageUrl);
        console.log(result);
    } catch (error) {
        loading_overlay.style.display = 'none';
        console.error(error);
    }
}

function toggleUnderline2(element) {
    if (element.classList.contains('colorize-light-gray')) {
        element.classList.remove('colorize-light-gray'); // 移除改变颜色的类
    } else {
        element.classList.add('colorize-light-gray'); // 添加改变颜色的类
    }
}
function toggleUnderline3(element) {
    if (element.classList.contains('colorize-light-gray')) {
        element.classList.remove('colorize-light-gray'); // 移除改变颜色的类
    } else {
        element.classList.add('colorize-light-gray'); // 添加改变颜色的类
    }
}